﻿<%@ Page Language="vb" AutoEventWireup="false" MasterPageFile="~/Admin/Masters/Members.master" Inherits="Boogaloo.Core.UI.BaseAdminPage" 
    title="Mindfly Web Studio's Boogaloo - Membership" %>
<%@ register tagprefix="boogaloo" assembly="Boogaloo.Admin" namespace="Boogaloo.Admin.UI.Controls" %>
<%@ import namespace="Boogaloo.Core.UI" %>
<script runat="server">
    '
    ' Boogaloo® - http://www.mindfly.com
    ' Copyright (c) 2008
    ' by Mindfly, Inc.
    '
    ' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
    ' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
    ' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
    ' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    '
    ' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
    ' of the Software.
    '
    ' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
    ' INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    ' DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    ' SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    ' SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
    ' WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
    ' THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    
    
    ''' <remarks>This is intensive and should be changed to false in 
    ''' sites that expect to have a large number of users as it requires a hacky fix
    ''' for the membership provider/profile provider interaction 
    ''' </remarks>
    Private _showMembersOnline As Boolean = True
    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        
        hyp_cancel.NavigateUrl = Request.Url.PathAndQuery
        hyp_add.NavigateUrl = String.Format("{0}Users.aspx", Groove.path_admin_membership)
        
        Try
            member = Membership.GetUser(New Guid(Request.QueryString("user")))
        Catch ex As Exception
            member = Nothing
        End Try
        
        lbl_savemessage.Visible = Groove.GetEventTargetClicked(Page) = lb_save.ClientID
       
        If Not Page.IsPostBack Then
            BindPage()
        End If
        
    End Sub
    
    
    
    
    Private Sub BindPage()
        
        rpt_roles.DataSource = Roles.GetAllRoles
        rpt_roles.DataBind()
        
        
        rpt_users.DataSource = Membership.GetAllUsers()
        rpt_users.DataBind()
        
        
        Dim prof As ProfileCommon = Nothing        
        If member IsNot Nothing Then
            ' this is an update
            lgd.InnerHtml = String.Format("Edit the Existing Member '{0}'", member.UserName)
            
            ' save the lastactivity date to preserve the isOnline property                   
            Dim lastactivity As DateTime = member.LastActivityDate
            
            prof = Profile.GetProfile(member.UserName)
            
            
            
            lbl_txt_username.Visible = False            
            h4_username.InnerHtml = member.UserName
            
            pnl_password.Visible = False
            txt_screenname.Text = prof.Boogaloo.ScreenName
            txt_email.Text = member.Email            
            
            dwiz_member.CommandArgument = member.UserName
            
            ' Begin custom profile fields
            ' ----------------------------------------
            
            ' ----------------------------------------
            ' End custom profile fields
            
  
            ' prevent someone from deleting themselves
            If Membership.GetUser().UserName.ToLower = member.UserName.ToLower Then dwiz_member.Visible = False
            
            pnl_info.Visible = True
            ' reset the lastactivity date
            If _showMembersOnline Then
                member.LastActivityDate = lastactivity
                Membership.UpdateUser(member)
                                  
                If member.IsOnline Then
                    lbl_online.Text = "Currently online"
                Else
                    lbl_online.Text = "Is not online"
                End If
            Else
                lbl_online.Visible = False
                lbl_lastactivity.Visible = False
            End If
            lbl_lastactivity.Text = String.Format("Last activity: {0}", member.LastActivityDate)
            lbl_lastlogin.Text = String.Format("Last login: {0}", member.LastLoginDate)
            
            
            If member.IsLockedOut Then
                chk_locked.Checked = True
                lb_changepw.Enabled = False
            Else
                chk_locked.Checked = False
                chk_locked.Enabled = False
                
            End If
            
        Else
            ' add a new user
            lgd.InnerHtml = "Create a New Member"
            h4_username.Visible = False
            lb_changepw.Visible = False
            dwiz_member.Visible = False
            pnl_info.Visible = False
        End If
        
    End Sub
    
   
    
    Protected Sub rpt_users_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs) Handles rpt_users.ItemDataBound
        
        Dim user As MembershipUser = CType(e.Item.DataItem, MembershipUser)
        If user IsNot Nothing Then
            
            Dim display_name As String = String.Empty
            Dim lastactivityfix As DateTime = user.LastActivityDate
            
            Dim prof As ProfileCommon = Profile.GetProfile(user.UserName)
            If prof IsNot Nothing Then display_name = prof.Boogaloo.ScreenName
            
            If _showMembersOnline Then
                user.LastActivityDate = lastactivityfix ' if number of members 
                Membership.UpdateUser(user)
            End If
            display_name = String.Format("<span>{1}</span> ({0})", display_name, user.UserName).Trim
            
            Dim hyp_user As HyperLink = CType(e.Item.FindControl("hyp_user"), HyperLink)
            hyp_user.Text = display_name
            hyp_user.NavigateUrl = String.Format("{0}Users.aspx?user={1}", Groove.path_admin_membership, user.ProviderUserKey.ToString)
            
        End If
        
    End Sub
    
    
    
    Protected Sub rpt_roles_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs) Handles rpt_roles.ItemDataBound
        
        Dim role As String = CType(e.Item.DataItem, String)
        
        If Not String.IsNullOrEmpty(role) Then
            
            Dim chk_role As CheckBox = CType(e.Item.FindControl("chk_role"), CheckBox)
            chk_role.Text = role
            
                       
            
            Dim dwiz As CommitWizard = CType(e.Item.FindControl("dwiz_role"), CommitWizard)
            If Not role = "Boogaloo Admin" Then
                dwiz.CommandArgument = role
            Else
                dwiz.Visible = False
            End If
            
            If member IsNot Nothing Then
                If Roles.IsUserInRole(member.UserName, role) Then chk_role.Checked = True
                
                ' assert the the current user cannot remove themselves from admin                
                If Membership.GetUser().UserName.ToLower = member.UserName.ToLower And chk_role.Checked And role = "Boogaloo Admin" Then
                    chk_role.Enabled = False
                    chk_role.ToolTip = "This role is disabled to prevent you from accidently removing yourself as an admin."
                End If
                chk_role.AutoPostBack = True
            Else
                chk_role.AutoPostBack = False
            End If
            
            
        End If
        
    End Sub
    
    
    Protected Sub lb_save_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lb_save.Click
        
        If Page.IsValid Then
                        
            Dim prof As ProfileCommon = Nothing
            If member IsNot Nothing Then
                ' this is an update
                
                
                prof = Profile.GetProfile(member.UserName)
                Dim old_screenname As String = prof.Boogaloo.ScreenName
                
                prof.Boogaloo.ScreenName = txt_screenname.Text
                
                ' Begin custom profile fields
                ' ----------------------------------------
            
                ' ----------------------------------------
                ' End custom profile fields
                
                prof.Save()
                
                member.Email = txt_email.Text
                
                lbl_savemessage.Text = "This member's account information has been updated"
                
                ' change the password if panel open
                If pnl_password.Visible Then
                    Dim temp_password As String = member.ResetPassword()
                    If member.ChangePassword(temp_password, txt_password.Text) Then
                        lbl_savemessage.Text &= " and the password has been changed."
                    Else
                        lbl_savemessage.Text &= " BUT the <em>password change failed</em>."
                    End If
                End If
                
                               
                Membership.UpdateUser(member)
                
                If member.IsLockedOut And chk_locked.Checked = False Then
                    member.UnlockUser()
                    
                End If
                
                If old_screenname <> prof.Boogaloo.ScreenName Then
                    Groove.RefreshPage()
                Else
                    BindPage()
                End If
                 
                
            Else
                
                chk_locked.Visible = False
                
                ' create a new membership user
                If txt_password.Text.Length > 4 Then
                    member = Membership.CreateUser(txt_username.Text.Trim, txt_password.Text, txt_email.Text)
                End If
            
                ' update the profile
                If member IsNot Nothing Then
                    prof = Profile.GetProfile(member.UserName)
                    prof.Boogaloo.ScreenName = txt_screenname.Text
                    prof.Save()
                End If
                
                ' add the initial roles (if any)
                Dim item As RepeaterItem = Nothing
                For Each item In rpt_roles.Items
                    Dim chk As CheckBox = CType(item.FindControl("chk_role"), CheckBox)
                    If chk.Checked Then
                        Roles.AddUserToRole(member.UserName, chk.Text)
                    End If
                Next
                                                
                Response.Redirect(String.Format("{0}Users.aspx?user={1}", Groove.path_admin_membership, member.ProviderUserKey.ToString))
            End If
        
            
        End If
        
        
    End Sub
    
    Protected Sub lb_changepw_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lb_changepw.Click
    
        If pnl_password.Visible Then
            lb_changepw.Text = "Reset this member's password"            
        Else
            lb_changepw.Text = "Woops, I don't really want to reset this password"
        End If
        pnl_password.Visible = Not pnl_password.Visible
    
    End Sub
       
    
    Protected Sub chk_role_CheckChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim chk As CheckBox = CType(sender, CheckBox)
        
        If member IsNot Nothing Then
                    
            If chk.Checked Then
                Roles.AddUserToRole(member.UserName, chk.Text)
            Else
                Roles.RemoveUserFromRole(member.UserName, chk.Text)
            End If
        
            BindPage()
        
        End If
        
    End Sub
    
  
    Protected Sub lht_newrole_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lht_newrole.Click
        
        If Page.IsValid Then
            
            Dim rlist As New ArrayList
            rlist.AddRange(Roles.GetAllRoles)
            If Not rlist.Contains(lht_newrole.Text.Trim) Then
                Roles.CreateRole(lht_newrole.Text.Trim)                
            End If
            lht_newrole.Text = String.Empty
        End If
        
        BindPage()
        
    End Sub
    
    Protected Sub dwiz_role_Click(ByVal sender As Object, ByVal e As EventArgs)
        
        Dim dwiz As CommitWizard = CType(sender, CommitWizard)
        
        Roles.DeleteRole(dwiz.CommandArgument, False)
        lbl_savemessage.Visible = False
        BindPage()
        
    End Sub
    
    Protected Sub dwiz_member_Click(ByVal sender As Object, ByVal e As EventArgs) Handles dwiz_member.Click
        
        Dim dwiz As CommitWizard = CType(sender, CommitWizard)        
        Membership.DeleteUser(dwiz.CommandArgument)
        
        Response.Redirect(String.Format("{0}Users.aspx", Groove.path_admin_membership))
        
    End Sub
    
    
    Private _member As MembershipUser
    Public Property member() As MembershipUser
        Get
            Return _member
        End Get
        Set(ByVal value As MembershipUser)
            _member = value
        End Set
    End Property

    
    
    
</script>    

<asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server">

<h3>Member Information</h3>

<asp:updatepanel id="up" runat="server">
<contenttemplate>
    
    <fieldset id="fld" runat="server" class="member box enriched active">
        
        <h3 id="lgd" runat="server" />
        <boogaloo:commitwizard id="dwiz_member" runat="server" message="<p>You are about to delete this member.</p><p>This action cannot be reversed. Are you sure?</p>" commit_text="Yes, I really want to delete this member" cancel_text="Woops, I did not mean to hit this button" start_text="Delete" />
        
        <h4 id="h4_username" runat="server" />
            
        <asp:label id="lbl_savemessage" runat="server" text="Saved" />
        
        <div class="tabIndex half">
            
            
            <asp:label id="lbl_txt_username" runat="server" associatedcontrolid="txt_username">
                <span>Username</span> <asp:textbox cssclass="longest" id="txt_username" runat="server" /> <asp:requiredfieldvalidator runat="server" id="rfv_txt_username" controltovalidate="txt_username" display="Dynamic" errormessage="Every member managed by Boogaloo must have a unique username." validationgroup="editmember" />                        
            </asp:label><!-- this is where the AJAX username message should go -->
            
            <asp:label id="lbl_txt_screenname" runat="server" associatedcontrolid="txt_screenname">
                <span>Screen Name</span> <asp:textbox CssClass="longest" id="txt_screenname" runat="server" />
                <span class="example">ex. John Smith or DaddyMac</span>
            </asp:label>
        </div>
        
        <div class="tabIndex half">
            <asp:label id="lbl_txt_email" runat="server" associatedcontrolid="txt_email">
                <span>Email</span> <asp:textbox CssClass="longest" id="txt_email" runat="server" /> <asp:requiredfieldvalidator id="rfv_txt_email" runat="server" controltovalidate="txt_email" display="Dynamic" errormessage="An email address is required for each member so that they may retrieve their password" validationgroup="editmember" />
            </asp:label><!-- this is where the javascript email address checker message should go -->
        </div>
        
        <div class="tabIndex half">
            <asp:panel id="pnl_password" runat="server">
            
                <asp:label id="lbl_txt_password" runat="server" associatedcontrolid="txt_password">
                    <span>Password</span> <asp:textbox CssClass="longest" id="txt_password" textmode="Password" runat="server" /> <asp:requiredfieldvalidator id="rfv_txt_password" runat="server" controltovalidate="txt_password" errormessage="A password is required for all users. Passwords must be at least 5 characters in length.  This value can be adjusted in the web.config file." display="Dynamic" validationgroup="editmember"  />                 
                </asp:label><!-- this is where the javascript password length message should go -->
                
                <asp:label id="lbl_txt_confirm" runat="server" associatedcontrolid="txt_confirm">
                    <span>Confirm Password</span> <asp:textbox CssClass="longest" id="txt_confirm" textmode="Password" runat="server" />
                    <asp:comparevalidator id="cmp_txt_confirm" runat="server" controltovalidate="txt_confirm" controltocompare="txt_password" operator="Equal" type="String" errormessage="The password and confirm password fields do not match." display="Dynamic" validationgroup="editmember"  />
                </asp:label> 
               
                                  
            </asp:panel>   
        </div>                   
        <asp:linkbutton CssClass="reset" id="lb_changepw" runat="server" text="Reset this member's password"  />
        
        <asp:checkbox id="chk_locked" runat="server" text="This account is locked" />
        
        <div id="buttons">
            <asp:linkbutton CssClass="button enriched save" id="lb_save" runat="server" text="Save" validationgroup="editmember" />
            <asp:hyperlink CssClass="button enriched cancel" id="hyp_cancel" runat="server" text="Cancel" />
        </div>
    
        <div id="divRoles" style="margin: 2em 0 1em 0">
        
            <h3 style="border-bottom: 1px solid #ccc">Roles</h3>
            <br />
            
            <asp:repeater id="rpt_roles" runat="server">
            <headertemplate><ul class="roles"></headertemplate>
            <itemtemplate>
            <li>
                <h4><asp:checkbox id="chk_role" runat="server" oncheckedchanged="chk_role_CheckChanged" /></h4>
                <ul class="toolbar">
                    <li class="tool delete"><boogaloo:commitwizard id="dwiz_role" cssclass="warning" runat="server" start_text="(x)" message="<p>You are about to delete this role for <strong><em>every</em></strong> website managed by Boogaloo.</p><p>This action cannot be reversed.</p>" cancel_text="I didn't mean to hit that button" commit_text="Yes, delete the role" onclick="dwiz_role_Click" /></li>
                </ul>
            </li>
            </itemtemplate>
            <footertemplate></ul></footertemplate>
            </asp:repeater>
            
            <boogaloo:labelhiddentextbox  id="lht_newrole" label="(Click to add a new role)" tooltip="Click to add a new role" validate="true" errormessage="You must provide a unique rolename" cssclass="inlineEdit editBoxHint" runat="server" />
          
  
        </div>
        
        
    
    </fieldset>

</contenttemplate>
</asp:updatepanel>
    
    
<h3 style="border-bottom: 1px solid #ccc;">Activity Snapshot</h3>

<asp:panel id="pnl_info" runat="server">
    <h4><asp:label id="lbl_online" runat="server" /></h4>
    <asp:label id="lbl_lastactivity" runat="server" /><br />
    <asp:label id="lbl_lastlogin" runat="server" />
</asp:panel>

</asp:Content>

<asp:Content ID="SubContent" ContentPlaceHolderID="SubContent" runat="server">

<div id="divPageSettings" class="box enriched alt">
    <h3>Members</h3>
    <asp:hyperlink id="hyp_add" runat="server" text ="Add member (+)" cssclass="button" />

    <asp:repeater id="rpt_users" runat="server">
        <headertemplate><ul class="nav buttons"></headertemplate>
        <itemtemplate><li>
        <asp:hyperlink id="hyp_user" runat="server" />
        </li></itemtemplate>
        <footertemplate></ul></footertemplate>
    </asp:repeater>
</div>
</asp:Content>
